package com.xiaolanshu.controller;

import com.xiaolanshu.entity.Dataurl;
import com.xiaolanshu.entity.Note;
import com.xiaolanshu.entity.NoteComment;
import com.xiaolanshu.entity.User;
import com.xiaolanshu.exception.BusinessException;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.service.DataurlService;
import com.xiaolanshu.service.NoteCommentService;
import com.xiaolanshu.service.NoteService;
import com.xiaolanshu.service.UserService;
import com.xiaolanshu.vo.ErrorResult;
import com.xiaolanshu.vo.NoteInfoVo;
import com.xiaolanshu.vo.NoteVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Slf4j
@RequestMapping("/found")
public class NoteController {

    @Autowired
    private NoteService noteService;
    @Autowired
    private NoteCommentService noteCommentService;
    @Autowired
    private DataurlService dataurlService;
    @Autowired
    private UserService userService;

    /**
     * 获取发现首页信息
     * @return
     */
    @GetMapping
    public ResponseEntity foundIndex(){

        //首页推荐视频，随机生成一组整数，根据这些整数查找笔记
        Random random = new Random();
        int[] array = new int[20]; // 创建一个长度为20的整型数组
        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(64) + 1; // 为每个元素赋值一个[1,64)之间的随机整数
        }

        List<Note> notes = noteService.noteArrList(array);
        //遍历推荐笔记列表,将用户信息和笔记信息封装到noteVoList
        List<NoteVo> recommendNoteVoList = new ArrayList<>();
        for (Note note:notes
        ) {
            //根据笔记用户id，获取用户信息
            User user = userService.findUser(note.getUserId());

            NoteVo noteVo = new NoteVo();
            noteVo.setNote(note);
            noteVo.setUser(user);

            recommendNoteVoList.add(noteVo);
        }

        //获取所有笔记信息
        List<Note> noteList = noteService.noteList();

        //遍历所有笔记,将用户信息和笔记信息封装到noteVoList
        List<NoteVo> allNoteVoList = new ArrayList<>();
        for (Note note:noteList
             ) {
            //根据笔记用户id，获取用户信息
            User user = userService.findUser(note.getUserId());

            NoteVo noteVo = new NoteVo();
            noteVo.setNote(note);
            noteVo.setUser(user);

            allNoteVoList.add(noteVo);
        }

        Map<String,List<NoteVo>> note = new HashMap<>();
        note.put("推荐笔记",recommendNoteVoList);
        note.put("所有笔记",allNoteVoList);

        return ResponseEntity.ok(note);
    }

    /**
     * 获取笔记内容
     * @param noteId
     * @return
     */
    @GetMapping("/content/{noteId}")
    public ResponseEntity noteContent(@PathVariable Long noteId){

        //从线程当中获取用户id和用户名（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        //创建VO对象并将查出的信息赋值
        NoteInfoVo noteInfoVo = new NoteInfoVo();

        //根据笔记id获取笔记内容
        Note noteContent = noteService.findNoteById(noteId);

        //根据用户id获取用户信息
        User user = userService.findUser(userId);

        //根据笔记id获取笔记评论
        List<NoteComment> commentList = noteCommentService.findCommentListById(noteId);

        //根据笔记id获取笔记的视频,如果查询出的视频不为空
        if (dataurlService.findVideo(noteId) != null) {
            Dataurl videourl = dataurlService.findVideo(noteId);
            noteInfoVo.setVideourl(videourl.getVideourl());
        }

        //根据笔记id获取笔记的图片，如果查询出的图片不为空
        if (dataurlService.findPictureListById(noteId) != null) {
            List<String> pictureurlList = dataurlService.findPictureListById(noteId);
            noteInfoVo.setPictureurl(pictureurlList);
        }
        //将要返回的笔记信息赋值VO对象
        noteInfoVo.setNoteId(noteContent.getId());
        noteInfoVo.setUsername(noteContent.getUsername());
        noteInfoVo.setContent(noteContent.getContent());
        noteInfoVo.setTitle(noteContent.getTitle());
        noteInfoVo.setTag(noteContent.getTag());
        noteInfoVo.setCollectionnum(noteContent.getCollectionnum());
        noteInfoVo.setPraiseNum(noteContent.getPraisenum());
        noteInfoVo.setComment(commentList);
        noteInfoVo.setHeadphoto(user.getHeadphoto());

        return ResponseEntity.ok(noteInfoVo);
    }

    /**
     * //根据笔记标题、内容、标签模糊查询
     * @param param
     * @return
     */
    @GetMapping("/search")
    public ResponseEntity search(@RequestParam String param){
        //根据笔记标题、内容、标签模糊查询
        List<NoteVo> noteList = noteService.searchList(param);
        return ResponseEntity.ok(noteList);
    }

    /**
     * 评论笔记
     * @param noteId
     * @param comment
     * @return
     */
    @PostMapping("/comment/{noteId}")
    public ResponseEntity comment(@PathVariable Long noteId, @RequestParam String comment){
        //保存评论信息
        int i = noteCommentService.saveComment(noteId, comment);
        if(!String.valueOf(i).equals("")){
            return ResponseEntity.status(200).body("保存成功");
        }
        else {
            //更新失败抛出自定义业务异常
            throw new BusinessException(ErrorResult.crudError());
        }
    }


}
